package entity;

import database.DatabaseHelper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class Teacher {

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    private Teacher(String id, String name) {
        this.id = id;
        this.name = name;
    }

    /* C */
    public static boolean create(DatabaseHelper db, String id, String name) throws SQLException {
        return db.update("insert into teacher(id,name) value (?,?)", id, name) > 0;
    }

    /* R */
    private static ArrayList<Teacher> findWhere(DatabaseHelper db, String condition, Object... params) throws SQLException {
        String query = "select id,name from teacher where " + condition;
        ResultSet rs = db.query(query, params);
        ArrayList<Teacher> teachers = new ArrayList<>();
        while (rs.next()) {
            teachers.add(new Teacher(rs.getString(1), rs.getString(2)));
        }
        rs.close();
        return teachers;
    }

    public static Teacher find(DatabaseHelper db, String id) throws SQLException {
        ArrayList<Teacher> teachers = findWhere(db, "id = ?", id);
        return teachers.isEmpty() ? null : teachers.get(0);
    }

    public static ArrayList<Teacher> findAll(DatabaseHelper db) throws SQLException {
        return findWhere(db, "true");
    }

    public ArrayList<Section> getSections(DatabaseHelper db) throws SQLException {
        return Section.findWhere(db, "tea_id = ?", id);
    }

    public boolean refresh(DatabaseHelper db) throws SQLException {
        Teacher tea = Teacher.find(db, id);
        if (tea == null)
            return false;
        name = tea.name;
        return true;
    }

    /* U */
    public boolean setAttribute(DatabaseHelper db, String attribute, Object value) throws SQLException {
        String update = "update teacher set " + attribute + " = ? where id = ?";
        int affectedRows = db.update(update, value, id);
        refresh(db);
        return affectedRows > 0;
    }

    public boolean setName(DatabaseHelper db, String name) throws SQLException {
        return setAttribute(db, "name", name);
    }

    /* D */
    public boolean delete(DatabaseHelper db) throws SQLException {
        return db.update("delete from teacher where id = ?", id) > 0;
    }

}
